package com.rtwo.simplenote.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.rtwo.simplenote.common.MD5Util;
import com.rtwo.simplenote.model.NoteModel;
import com.rtwo.simplenote.model.UserModel;

/**
 * 
 * 本实例最大的关注点在于异步请求和session的应用以及数据库的操作
 *
 */
public class MainController extends Controller{
	
	/**
	 * 登陆和注册界面
	 */
	public void index(){
		render("login.html");
	}
	
	/**
	 * 登陆处理
	 */
	public void login(){
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		String userName = getPara("simnote.userName");
		String passWord = getPara("simnote.passWord");
		Record userRecord = Db.findFirst("select * from user where userName = ? and passWord = ?",userName,MD5Util.MD5(passWord));
		if(userRecord==null){
			renderJson("info","登陆失败");
		}
		else{
			getSession().setAttribute("userRecord", userRecord);
			//为什么不直接在这里进行setAttr,把userRecord传进去?因为setAttr是依赖页面的,所以我们在userInterface中进行该操作
			long userId = userRecord.getLong("userId");
			List<NoteModel> noteRecord = NoteModel.noteTable.find("select * from note where userId = ?",userId);
			getSession().setAttribute("noteRecord", noteRecord);
			renderJson("info","sucess");
		}
	}
	
	/**
	 * 用户界面,包括笔记展示,写笔记,删除笔记
	 */
	public void userInterface(){
		setAttr("userInfo",getSession().getAttribute("userRecord"));
		setAttr("noteInfo",getSession().getAttribute("noteRecord"));
		render("userInterface.jsp");	
	}
	
	/**
	 * 处理注册的流程，包括判断用户名，密码是否符合要求，判断是否有该用户；
	 * 如果成功，则响应sucess，并写入数据库；
	 * 如果失败，则响应错误语句，不进行操作
	 */
	public void register(){
		List<UserModel> userList = new ArrayList<UserModel>();
		String userName = getPara("simnote.userName");
		String passWord = getPara("simnote.passWord");
		long deviceType = getParaToLong("simnote.deviceType");
		long notesNumber = 0;
		if(userName.matches("\\w{1,12}")){
			if(passWord.matches(".{6}")){
				userList = UserModel.userTable.find("select userName from user");
				Iterator<UserModel> userIterator = userList.iterator();
				while(userIterator.hasNext()){
					String existedName = userIterator.next().get("userName");
					if(existedName.equals(userName)){
						renderJson("info","该用户名存在");
						return;
					}
				}
				storeUserData(userName,passWord,0,notesNumber,deviceType);
				renderJson("info","sucess");
			}
			else{
				renderJson("info","密码必须为6个字符");
			}
		}
		else{
			renderJson("info","用户名必须为1到12个字符");
		}
	}
	
	/**
	 * 存储用户数据到数据库
	 */
	public void storeUserData(String userName,String passWord,int isAdmin,long noteNumber,long deviceType){
		Record user = new Record().set("userId",deviceType)
							.set("userName", userName)
							.set("passWord", MD5Util.MD5(passWord))
							.set("isAdmin", isAdmin)
							.set("registerTime",new Date())
							.set("notesNumber", noteNumber);
		Db.save("user",user);
		Db.update("update user set userId = userId+Id where userName = ?",userName);
	}
	
	/**
	 * 笔记的记录
	 */
	public void writeNotes(){
		setAttr("userInfo",getSession().getAttribute("userRecord"));
		render("writeNotes.jsp");
	}
	
	/**
	 * 保存笔记并更新user的noteNumber字段
	 */
	public void saveNotes(){
		String noteTitle = getPara("noteTitle");
		String noteContent = getPara("noteContent");
		long userId = getParaToLong("userId");
		Record noteRecord = new Record();
		noteRecord.set("userId",userId)
					.set("noteName", noteTitle)
					.set("content", noteContent)
					.set("createdTime", new Date())
					.set("lastModified",new Date());
		boolean action = Db.save("note", noteRecord);
		if(action==true){
			UserModel userModel = UserModel.userTable.findFirst("select * from user where userId = ?",userId);
			int notesNumber = userModel.getInt("notesNumber");
			userModel.set("notesNumber", notesNumber+1).update();
			getSession().setAttribute("userRecord", userModel);
			List<NoteModel> noteModel = NoteModel.noteTable.find("select * from note where userId = ?",userId);
			System.out.println(noteModel);
			getSession().setAttribute("noteRecord", noteModel);
			renderJson("info","sucess");
		}
		else{
			renderJson("info","fail");
		}
	}
	
	/**
	 * 笔记展示
	 */
	public void showNotes(){
		String id = getPara(0);
		Record note = Db.findFirst("select * from note where noteId = ?",id);
		setAttr("note",note);
		render("show.jsp");
	}
	
	/**
	 * 注销
	 */
	public void logout(){
		getSession().invalidate();
		render("login.html");
	}
	/**
	 * 删除笔记和更新user表的notesNumber字段
	 */
	public void deleteNotes(){
		long id = getParaToLong(0);
		long userId = NoteModel.noteTable.findFirst("select * from note where noteId = ?",id).getLong("userId");
		Db.deleteById("note","noteId", id);
		UserModel userModel = UserModel.userTable.findFirst("select * from user where userId = ?",userId);
		int notesNumber = userModel.getInt("notesNumber");
		userModel.set("notesNumber", notesNumber-1).update();
		List<Record> list =Db.find("select * from note where userId = ?",userId);
		setAttr("userInfo", userModel);
		setAttr("noteInfo",list);
		render("userInterface.jsp");
	}
}
